package com.efounder.form.service;

import com.efounder.builder.base.data.EFRowSet;
import com.efounder.eai.data.JParamObject;
import com.efounder.form.base.DataComponent;
import com.efounder.form.base.IComponent;
import com.efounder.message.db.MessageDBHelper;
import com.efounder.message.db.MessageDBManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.service.IService;
import com.efounder.util.AppContext;

import net.sf.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.Iterator;

import static com.efounder.builder.base.json.JSONUtil.JSON2Object;

/**
 * Created by Javor on 16/9/27.
 */

public class MDModelDBLoadService extends DataComponent implements IService, IComponent {
    private String msgID;
    private String key;

    @Override
    public Object executeService(JParamObject po, Object dao, Object co, Object userObject,
                                 Object ao) {
//        MessageDBHelper sqlHelper = new MessageDBHelper(AppContext.getInstance());
//        MessageDBManager dbManager = new MessageDBManager(sqlHelper);
        MessageDBManager dbManager = MessageDBManager.getInstance();

        IMStruct002 imStruct002 = dbManager.queryForID(msgID);
        String json = null;
        try {
            if (imStruct002 != null) {
                json = new String(imStruct002.getBody(), "UTF-8");
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        EFRowSet rowSet = JSON2RowSet(json, key);
        return rowSet;
    }

    public String getmsgID() {
        return msgID;
    }

    public void setmsgID(String msgID) {
        this.msgID = msgID;
    }

    private String id;

    @Override
    public String getID() {
        return id;
    }

    @Override
    public void setID(String id) {
        this.id = id;
    }

    @Override
    public void creationComplete() {

    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public EFRowSet JSON2RowSet(String jsonStr, String needKey) {
        EFRowSet rowSet = EFRowSet.getInstance();
        JSONObject jsonObject = JSON2Object(jsonStr);
        Iterator iter;
        String key;
        if (jsonStr == null) {
            return null;
        }
        if (jsonObject.get("_Self_RowSet") == null) {
            iter = jsonObject.keys();

            while (iter.hasNext()) {
                key = (String) iter.next();
                if (key.equals(needKey)) {
                    rowSet.put(key, jsonObject.get(key));
                }

            }
        }

        return rowSet;
    }
}
